package com.yichen.ycapiGateway.filter;

import com.yichen.ycApiCommon.model.entity.InterfaceInfo;
import com.yichen.ycApiCommon.model.entity.User;
import com.yichen.ycApiCommon.model.entity.UserInterfaceInfo;
import com.yichen.ycApiCommon.model.enums.InterfaceStatusEnum;
import com.yichen.ycApiCommon.service.InnerInterfaceInfoService;
import com.yichen.ycApiCommon.service.InnerUserInterfaceInfoService;
import com.yichen.ycApiCommon.service.InnerUserService;
import com.yichen.ycapiclientSDK.utils.SignUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * @Author: yichenwu
 * @Date:2024/7/30 16:54
 */

/**
 * 全局过滤器
 */
@Component
@Slf4j
public class CustomGlobalFilter implements GlobalFilter, Ordered {

    public static final List<String> IP_WHITE_LIST = Arrays.asList("127.0.0.1");

    @Resource
    private InnerUserService innerUserService;
    @Resource
    private InnerUserInterfaceInfoService innerUserInterfaceInfoService;
    @Resource
    private InnerInterfaceInfoService innerInterfaceInfoService;

    // 该用户是否还有调用次数
    public static Boolean IS_HAVE_LEFT_NUM = false;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 2. 请求日志
        ServerHttpRequest request = exchange.getRequest();
        log.info("请求唯一标识: {}", request.getId());
        log.info("请求方法: {}", request.getMethod());
        log.info("请求路径: {}", request.getPath().value());
        log.info("请求参数: {}", request.getQueryParams());
        String hostString = request.getLocalAddress().getHostString();
        log.info("请求来源地址1: {}", hostString);
        log.info("请求来源地址: {}", request.getRemoteAddress());
        // 3. （黑白名单）
        ServerHttpResponse response = exchange.getResponse();
        if (!IP_WHITE_LIST.contains(hostString)) {
            // 直接设置状态码为403（禁止访问）
            return handleNoAuth(response, IS_HAVE_LEFT_NUM);
        }
        // 4. 用户鉴权（判断 ak、sk 是否合法）
        HttpHeaders headers = request.getHeaders();
        String accessKey = Optional.ofNullable(headers.getFirst("accessKey")).orElse(" ");
        String nonce = Optional.ofNullable(headers.getFirst("nonce")).orElse(" ");
        String timestamp = Optional.ofNullable(headers.getFirst("timestamp")).orElse(" ");
        String sign = Optional.ofNullable(headers.getFirst("sign")).orElse(" ");
        String requestBody = Optional.ofNullable(headers.getFirst("requestBody")).orElse(" ");
        // todo 实际情况应该是去数据库中查是否已分配给用户
        User invokeUser = null;
        try {
            invokeUser = innerUserService.getInvokeUser(accessKey);
        } catch (Exception e) {
            log.error("getInvokeUser error", e);
        }
        if (ObjectUtils.isEmpty(invokeUser)) {
            return handleNoAuth(response, IS_HAVE_LEFT_NUM);
        }
        // 校验随机数,模拟一下,直接判断nonce是否大于10000
        if (Long.parseLong(nonce) > 10000L) {
            return handleNoAuth(response, IS_HAVE_LEFT_NUM);
        }
        // 时间和当前时间不能超过5分钟
        final long FIVE_MINUTES = 60 * 5L;
        if ((System.currentTimeMillis() / 1000) - Long.parseLong(timestamp) >= FIVE_MINUTES) {
            return handleNoAuth(response, IS_HAVE_LEFT_NUM);
        }
        String serverSign = SignUtils.getSign(requestBody, invokeUser.getSecretKey());
        if (StringUtils.isEmpty(invokeUser.getSecretKey()) || !serverSign.equals(sign)) {
            return handleNoAuth(response, IS_HAVE_LEFT_NUM);
        }
        // 5. 请求的模拟接口是否存在？
        InterfaceInfo invokeInterfaceInfo = null;
        try {
            invokeInterfaceInfo = innerInterfaceInfoService.getInvokeInterfaceInfo(request.getPath().value(), request.getMethod().toString());
        } catch (Exception e) {
            log.error("getInvokeInterfaceInfo error", e);
        }
        if (ObjectUtils.isEmpty(invokeInterfaceInfo) || invokeInterfaceInfo.getStatus().equals(InterfaceStatusEnum.OFFLINE.getValue())) {
            return handleNoAuth(response, IS_HAVE_LEFT_NUM);
        }
        // 6. 请求转发，调用模拟接口
        // 异步的导致业务逻辑不正确
//        Mono<Void> filter = chain.filter(exchange);
        log.info("网关全局过滤器 global filter");

        // 判断用户是否还有调用次数
        UserInterfaceInfo userInterfaceInfo = innerUserInterfaceInfoService.invokeUserInterfaceInfo(invokeInterfaceInfo.getId(), invokeUser.getId());
        if (userInterfaceInfo.getLeftNum() <= 0) {
            IS_HAVE_LEFT_NUM = true;
            return handleNoAuth(response, IS_HAVE_LEFT_NUM);
        }
        return handleResponse(exchange, chain, invokeInterfaceInfo.getId(), invokeUser.getId());
    }

    @Override
    public int getOrder() {
        return -1;
    }

    /**
     * 无权限处理
     *
     * @param response
     * @return
     */
    public Mono<Void> handleNoAuth(ServerHttpResponse response, Boolean judgeLeftNum) {
        if (judgeLeftNum) {
            // 没有调用次数
            // 直接设置状态码为400
            response.setStatusCode(HttpStatus.BAD_REQUEST);
        } else {
            // 直接设置状态码为403（禁止访问）
            response.setStatusCode(HttpStatus.FORBIDDEN);
        }
        // 处理完成的响应 -- 返回的 Mono 是异步的 类似 前端的 promise
        return response.setComplete();
    }

    /**
     * 调用接口失败
     *
     * @param response
     * @return
     */
    public Mono<Void> handleInvokeError(ServerHttpResponse response) {
        // 直接设置状态码为500
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        // 处理完成的响应 -- 返回的 Mono 是异步的 类似 前端的 promise
        return response.setComplete();
    }

    /**
     * 处理响应
     *
     * @param exchange
     * @param chain
     * @return
     */
    public Mono<Void> handleResponse(ServerWebExchange exchange, GatewayFilterChain chain, Long interfaceInfoId, Long userId) {
        try {
            // 获取原始的响应对象
            ServerHttpResponse originalResponse = exchange.getResponse();
            // 获取数据缓冲工厂
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            // 获取响应的状态码
            HttpStatus statusCode = originalResponse.getStatusCode();

            // 判断状态码是否为200 OK(按道理来说,现在没有调用,是拿不到响应码的,对这个保持怀疑 沉思.jpg)
            if (statusCode == HttpStatus.OK) {
                // 创建一个装饰后的响应对象(开始穿装备，增强能力)
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {

                    // 重写writeWith方法，用于处理响应体的数据
                    // 这段方法就是只要当我们的模拟接口调用完成之后,等它返回结果，
                    // 就会调用writeWith方法,我们就能根据响应结果做一些自己的处理
                    @Override
                    // 6. 请求转发，调用模拟接口
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        log.info("body instanceof Flux: {}", (body instanceof Flux));
                        // 判断响应体是否是Flux类型
                        if (body instanceof Flux) {
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            // 返回一个处理后的响应体
                            // (这里就理解为它在拼接字符串,它把缓冲区的数据取出来，一点一点拼接好)
                            return super.writeWith(fluxBody.handle((dataBuffer, sink) -> {
                                // 读取响应体的内容并转换为字节数组
                                byte[] content = new byte[dataBuffer.readableByteCount()];
                                dataBuffer.read(content);
                                DataBufferUtils.release(dataBuffer);//释放掉内存
                                // 构建日志
                                // HttpStatus statusCode = response.getStatusCode();
                                // log.info("响应：{}", statusCode);
                                StringBuilder sb2 = new StringBuilder(200);
//                                sb2.append("<--- {} {} \n");
                                List<Object> rspArgs = new ArrayList<>();
                                rspArgs.add(originalResponse.getStatusCode());
                                //rspArgs.add(requestUrl);
                                String data = new String(content, StandardCharsets.UTF_8);//data

                                // 8. 调用成功，接口调用次数 + 1
                                Boolean aBoolean = false;
                                try {
                                    aBoolean = innerUserInterfaceInfoService.invokeCountPlus(interfaceInfoId, userId);
                                    log.info("接口调用次数加一是否成功：{}", aBoolean);
                                } catch (Exception e) {
                                    log.error("invokeCountPlus error", e);
                                }
                                sb2.append(data);
//                                log.info(sb2.toString(), rspArgs.toArray());//log.info("<-- {} {}\n", originalResponse.getStatusCode(), data);
                                // 7. 响应日志
                                log.info("响应结果：{}", data);//log.info("<-- {} {}\n", originalResponse.getStatusCode(), data);
                                // 将处理后的内容重新包装成DataBuffer并返回
                                sink.next(bufferFactory.wrap(content));
                            }));
                        } else {
                            log.error("<--- {} 响应code异常", getStatusCode());
                        }
                        return super.writeWith(body);
                    }
                };
                // 对于200 OK的请求,将装饰后的响应对象传递给下一个过滤器链,并继续处理(设置repsonse对象为装饰过的)
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            // 对于非200 OK的请求，直接返回，进行降级处理
            return chain.filter(exchange);
        } catch (Exception e) {
            // 处理异常情况，记录错误日志
            log.error("gateway 处理响应 exception.\n" + e);
            return chain.filter(exchange);
        }
    }

}

